﻿using Nop.Admin.Extensions;
using Nop.Admin.Models.Customers;
using Nop.Admin.Models.Directory;
using Nop.Core;
using Nop.Core.Domain.Directory;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Security;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Admin.Controllers
{
    public class OrganizationController : BaseAdminController
    {
        #region Fields

        private readonly ICustomerActivityService _customerActivityService;
        private readonly IPermissionService _permissionService;
        private readonly IOrganizationService _organizationService;

        #endregion

        #region Constructors

        public OrganizationController(
            ICustomerActivityService customerActivityService,
            IPermissionService permissionService,
            IOrganizationService organizationService
            )
        {
            this._customerActivityService = customerActivityService;
            this._permissionService = permissionService;
            this._organizationService = organizationService;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected virtual OrganizationModel PrepareOrganizationModel(Organization organization)
        {
            return new OrganizationModel
            {
                Id = organization.Id,
                Name = organization.Name,
                Address = organization.Address,
                ContactWay = organization.ContactWay,
                Active = organization.Active
            };
        }

        #endregion

        #region Customer roles

        public virtual ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public virtual ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedView();

            return View();
        }

        [HttpPost]
        public virtual ActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedKendoGridJson();

            var organizations = _organizationService.GetAllOrganizations();
            var gridModel = new DataSourceResult
            {
                Data = organizations.Select(PrepareOrganizationModel),
                Total = organizations.Count()
            };

            return Json(gridModel);
        }

        public virtual ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedView();

            var model = new OrganizationModel
            {
                Active = true
            };
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public virtual ActionResult Create(OrganizationModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                var organization = new Organization
                {
                    Name = model.Name,
                    Address = model.Address,
                    ContactWay = model.ContactWay,
                    Active = model.Active
                };
                _organizationService.InsertOrganization(organization);

                //activity log
                _customerActivityService.InsertActivity("AddNewOrganization", "新增单位 Id={0}", organization.Id);

                SuccessNotification("新增单位成功");
                return continueEditing ? RedirectToAction("Edit", new { id = organization.Id }) : RedirectToAction("List");
            }

            return View(model);
        }

        public virtual ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedView();

            var organization = _organizationService.GetOrganizationById(id);
            if (organization == null)
                return RedirectToAction("List");

            var model = PrepareOrganizationModel(organization);
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public virtual ActionResult Edit(OrganizationModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedView();

            var organization = _organizationService.GetOrganizationById(model.Id);
            if (organization == null)
                return RedirectToAction("List");

            try
            {
                if (ModelState.IsValid)
                {
                    organization.Name = model.Name;
                    organization.Address = model.Address;
                    organization.ContactWay = model.ContactWay;
                    organization.Active = model.Active;
                    _organizationService.UpdateOrganization(organization);

                    //activity log
                    _customerActivityService.InsertActivity("EditOrganization", "编辑单位 Id={0}", organization.Id);

                    SuccessNotification("编辑单位成功");
                    return continueEditing ? RedirectToAction("Edit", new { id = organization.Id }) : RedirectToAction("List");
                }

                return View(model);
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
                return RedirectToAction("Edit", new { id = organization.Id });
            }
        }

        [HttpPost]
        public virtual ActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrganizations))
                return AccessDeniedView();

            var organization = _organizationService.GetOrganizationById(id);
            if (organization == null)
                return RedirectToAction("List");

            try
            {
                organization.Deleted = true;
                _organizationService.UpdateOrganization(organization);

                //activity log
                _customerActivityService.InsertActivity("DeleteOrganization", "删除单位 Id={0}", organization.Id);

                SuccessNotification("删除单位成功");
                return RedirectToAction("List");
            }
            catch (Exception exc)
            {
                ErrorNotification(exc.Message);
                return RedirectToAction("Edit", new { id = organization.Id });
            }

        }

        #endregion
    }
}